
const axios = require("axios");

let  WX_TOKEN = '';
const wxAppID='wx0f8856d0e95f7eec';
const wxAppSecret='cc85e09fca339df80c860a1c073f149f';

(function initWeixin() {
    axios.get(`https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=${wxAppID}&secret=${wxAppSecret}`)
        .then(response => {
            const {access_token, expires_in, errcode} = response.data;
            if (errcode) throw response.data;
            WX_TOKEN = access_token;
            setTimeout(() => initWeixin(), (expires_in - 600) * 1000);//提前十分钟更新ACCESS_TOKEN
        }).catch(err => {
        console.error("获取微信Token失败:", err);
        setTimeout(() => initWeixin(), 30000);//30秒重试
    });
})();
function sendWxMessage(studentName,schoolName,datetimeStr,imageUrl,openIds){
    const msgActions = openIds.map(item=> {
        return axios.post(`https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=${WX_TOKEN}`, {
            touser: item,
            template_id: 'fAJiIf0HZhIC7Z7Y7Gv3MIoM6_kvZ-2LMo7gHd-VYyo',
            url: imageUrl,
            data: {
                first: {value: '您的孩子已在校区签到！',},//第一行内容
                keyword1: {value: studentName,},//姓名：
                keyword2: {value: schoolName,},//签到地点：
                keyword3: {value: datetimeStr,},//签到时间：
                remark: {value: '点击详情查看签到照片',},//最后一行内容
            }
        });
    });
    return Promise.all(msgActions);
}

module.exports = async (ctx, next) => {
    await next();
    if(ctx.response.status===200){
        const { student:std,time, imgUrl } = ctx.response.body;
        console.error("student,time, imgUrl",std,time, imgUrl);
        const student = await strapi.services.student.fetch({id:std.id});
        console.error("student", student);
        const parents = await strapi.services.parent.fetchAll({tel:student.tel});
        const openIds = parents.map(item=>item.openId);
        await sendWxMessage(student.name,student.device.name,time,imgUrl,openIds);
    }
};
